import type { ObjectDirective } from 'vue';
const HANDLER = '_vue_chart_resize_handler'
import echarts from './echartsUi'
import { nextTick } from 'vue'
import { useDebounceFn } from '@vueuse/core'

export const onEchartResize: ObjectDirective = {
  mounted(el) {
    el[HANDLER] = function () {
      setTimeout(() => {
        nextTick(() => {
          const chart = echarts.getInstanceByDom(el)
          if (!chart) return
          chart.resize()
        })
      }, 200)
    }
    const debouncedFn = useDebounceFn(() => {
      el[HANDLER]()
    }, 300)
    window.addEventListener('resize', debouncedFn)
  },
  updated(el) {
    window.removeEventListener('resize', el[HANDLER])
    delete el[HANDLER]
  }
};
